package com.charles.seckillPlatform.config;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.charles.seckillComponentCommon.constants.ErrorConstants;
import com.charles.seckillComponentCommon.exceptions.ServiceException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * platform 服务全局拦截器-限流
 */
public class PlatformControlInterceptor extends HandlerInterceptorAdapter {

    private static final String GLOBAL_RESOURCE = "GlobalResource";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        Entry entry = null;
        try {
            entry = SphU.entry(GLOBAL_RESOURCE);
            return true;
        } catch (BlockException e) {
            // 处理被限流的情况
            handleBlockException(request, response, e);
            return false;
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }

    private void handleBlockException(HttpServletRequest request, HttpServletResponse response, BlockException e) {
        Tracer.trace(e);
        throw new ServiceException(ErrorConstants.BLOCKING_ERROR);
    }
}
